package com.py.framework.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.py.framework.common.Constants;
import com.py.framework.common.controller.SystemController;
import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.core.rest.support.RestServiceResult;
import com.py.framework.entity.UserEntity;
import com.py.framework.entity.WorkFlowBus;
import com.py.framework.service.UserService;
import com.py.framework.service.WorkFlowService;

/**
 * 工作流Controller
 * 
 * @author Leegern
 * @date 2018年6月19日
 */
@RestController
@RequestMapping("/workflow")
public class WorkFlowController extends SystemController {

	/** 工作流Service实体 **/
	@Autowired
	private WorkFlowService workFlowService;

	@Autowired
	private HistoryService historyService;

	@Autowired
	private UserService userService;

	/**
	 * @api {post} /workflow/addWorkflow.json 添加工作流
	 * @apiName addWorkflow
	 * @apiVersion 0.0.1
	 * @apiGroup 工作流对外接口
	 * @apiParam {WorkFlowBus} entity 实例对象
	 * @apiParam {String} wfKey 工作流程实例KEY(必填)
	 * @apiParam {String} accessKey 接入Key
	 * @apiParam {long} userId 发起人ID
	 * @apiParam {long} sysId 系统ID
	 * @apiParam {long} busId 业务ID
	 * @apiParam {String} busName 业务名称
	 * @apiParam {String} busUrl 业务URL
	 * @apiParam {int} busType 业务类别
	 * @apiParam {String} remark 备注
	 * @apiParamExample {json} 请求参数示例
	 *                  {"wfKey":"123","accessKey":"13","userId":100,"sysId":"10","busId":"99","busName":"请假","busUrl":"http://xxx.com/print.do","busType":1,"remark":"请假流程"}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} wfId 流程ID
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":{"wfId":10001}}
	 */
	@RequestMapping(value = "/addWorkflow.do")
	public RestServiceResult<Map<String, Object>> addWorkflow(@RequestBody WorkFlowBus entity) {
		RestServiceResult<Map<String, Object>> result = new RestServiceResult<Map<String, Object>>();
		Map<String, Object> map = new HashMap<>();
		try {
			if (null != entity && StringUtils.isNotBlank(entity.getWfKey())) {
				workFlowService.addWorkFlowBus(entity);
				result.setCode(RestServiceResult.CODE_SUCCESS);
			}
		} catch (Exception e) {
			ExceptionLogger.error(e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("添加流程失败！");
		}
		map.put("wfId", entity.getId());
		return result;
	}

	/**
	 * @api {post} /workflow/startWorkflow.json 启动流程
	 * @apiName startWorkflow
	 * @apiVersion 0.0.1
	 * @apiGroup 工作流对外接口
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/startWorkflow.do")
	public RestServiceResult<Map<String, Object>> startWorkflow() {
		RestServiceResult<Map<String, Object>> result = new RestServiceResult<Map<String, Object>>();
		try {
			workFlowService.startWorkflow();
			result.setCode(RestServiceResult.CODE_SUCCESS);
		} catch (Exception e) {
			ExceptionLogger.error(e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("流程启动失败！");
		}
		return result;
	}

	@RequestMapping(value = "/getLastAssignee.do")
	public RestServiceResult<UserEntity> getLastAssi(@RequestParam(value = "processId") String processId) {
		RestServiceResult<UserEntity> result = new RestServiceResult<UserEntity>();
		HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery().processInstanceId(processId);
		HistoricTaskInstance singleResult = query.singleResult();
		String assignee = singleResult.getAssignee();
		UserEntity user = userService.findOneUser(Long.valueOf(assignee));
		result.setData(user);
		return result;
	}

	/**
	 * @api {get} /workflow/getActByWFId.json 根据流程Id获取数据
	 * @apiName getActByWFId
	 * @apiVersion 0.0.1
	 * @apiGroup 工作流对外接口
	 * @apiParam {int} wfId 流程Id
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} wfKey 工作流程实例KEY
	 * @apiSuccess {String} accessKey 接入Key
	 * @apiSuccess {long} userId 发起人ID
	 * @apiSuccess {long} sysId 系统ID
	 * @apiSuccess {long} busId 业务ID
	 * @apiSuccess {String} busName 业务名称
	 * @apiSuccess {String} busUrl 业务URL
	 * @apiSuccess {int} busType 业务类别
	 * @apiSuccess {String} remark 备注
	 * @apiSuccess {int} proStatus 流程状态，1：待审核; 2：审核; 3：通过; 4：不通过
	 * @apiSuccess {long} finishTime 完成时间
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":{"wfKey":"123","accessKey":"13","userId":100,"sysId":"10","busId":"99","busName":"请假","busUrl":"http://xxx.com/print.do","busType":1,"proStatus":1,"finishTime":1525244806000}}
	 */
	@RequestMapping(value = "/getActByWFId.do", method = RequestMethod.POST)

	public RestServiceResult<WorkFlowBus> getActByWFId(long wfId) {
		WorkFlowBus entity = null;
		if (wfId > Constants.NUMBER_ZERO) {
			entity = workFlowService.getActByWFId(wfId);
		}
		return super.getSuccessRestServiceResult(entity);
	}

	/**
	 * @api {post} /workflow/getActsByBusId.json 根据业务Id获取数据
	 * @apiName getActsByBusId
	 * @apiVersion 0.0.1
	 * @apiGroup 工作流对外接口
	 * @apiParam {long} busId 业务Id
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} wfKey 工作流程实例KEY
	 * @apiSuccess {String} accessKey 接入Key
	 * @apiSuccess {long} userId 发起人ID
	 * @apiSuccess {long} sysId 系统ID
	 * @apiSuccess {long} busId 业务ID
	 * @apiSuccess {String} busName 业务名称
	 * @apiSuccess {String} busUrl 业务URL
	 * @apiSuccess {int} busType 业务类别
	 * @apiSuccess {String} remark 备注
	 * @apiSuccess {int} proStatus 流程状态，1：待审核; 2：审核; 3：通过; 4：不通过
	 * @apiSuccess {long} finishTime 完成时间
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":{"wfKey":"123","accessKey":"13","userId":100,"sysId":"10","busId":"99","busName":"请假","busUrl":"http://xxx.com/print.do","busType":1,"proStatus":1,"finishTime":1525244806000}}
	 */
	@RequestMapping(value = "/getActsByBusId.do", method = RequestMethod.POST)
	public RestServiceResult<List<WorkFlowBus>> getActsByBusId(long busId) {
		List<WorkFlowBus> datas = null;
		if (busId > Constants.NUMBER_ZERO) {
			datas = workFlowService.getActsByBusId(busId);
		}
		return super.getSuccessRestServiceResult(datas);
	}

	@RequestMapping(value = "/getHandledWorkFlowBus.do")
	public RestServiceResult<List<WorkFlowBus>> getHandledWorkFlowBus() {

		List<WorkFlowBus> getHandledWorkFlowBus = workFlowService.getHandledWorkFlowBus();
		return super.getSuccessRestServiceResult(getHandledWorkFlowBus);
	}

	@RequestMapping(value = "/updateWorkFlowBusUpdateFlag.do", method = RequestMethod.POST)
	public RestServiceResult<String> updateWorkFlowBusUpdateFlag(@RequestParam String id) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		workFlowService.updateWorkFlowUpdateFlag(id);
		return result;
	}

	/**
	 * 获取数据拥有者
	 * @param taskId
	 * @return
	 */
	@RequestMapping(value = "/getDataOwnerByTaskId", method = RequestMethod.POST)
	public RestServiceResult<Integer> getDataOwnerByTaskId(String taskId){
		return super.getSuccessRestServiceResult(workFlowService.getDataOwnerByTaskId(taskId));
	}

	/**
	 * 远程调用获取工作流异议处理业务id
	 * @param taskId
	 * @return
	 */
	@RequestMapping(value = "/getBusIdByTaskId.do", method = RequestMethod.POST)
	public RestServiceResult<Integer> getBusIdByTaskId(@RequestParam String taskId) {
		return super.getSuccessRestServiceResult(workFlowService.getBusIdByTaskId(taskId));
	}

	/**
	 * 功能描述: 远程调用工作流获取当前企业异议处理数据
	 *
	 * @param key 工作流key
	 * @return
	 * @author YaoS
	 * @date 19/1/23 14:30
	 */
	@RequestMapping(value = "/getDissentProcessHistory.do", method = RequestMethod.POST)
	public RestServiceResult<WorkFlowBus> getDissentProcessHistory(
			@RequestParam String key,@RequestParam String id) {
		return super.getSuccessRestServiceResult(workFlowService.getDissentProcessHistory(key,id));
	}

}